//
//  MainEcgVc.m
//  CareRingApp
//
//  Created by Linktop on 2024/4/12.
//

#import "MainEcgVc.h"
#import "ConfigModel.h"
#import <Masonry/Masonry.h>
#import <QMUIKit/QMUIKit.h>
#import "DeviceCenter.h"
//#import "AccountCenter.h"
#import "DBEcgRecord.h"
#import "EcgListCell.h"
#import "BasicCalendaVc.h"
#import "EcgMeasureVc.h"
#import "NormalSetCell.h"
#import "EcgListCell.h"
#import "TimeUtils.h"
#import "NotificationNameHeader.h"
#import "UILabel+LNCTitleStyle.h"
#import "EcgDetailVc.h"
#import "EcgRecordsVc.h"
#import "UIViewController+Custom.h"

#import "UITableViewCell+Styles.h"

const NSInteger MAIN_ECG_RES_ALL_DATA = 100;

typedef NS_ENUM(NSUInteger, ECG_SEC) {
    ECG_SEC_ITEM,
    ECG_SEC_RESULTS,
    ECG_SEC_MEASU,
};


@interface MainEcgVc ()<UITableViewDelegate, UITableViewDataSource>
@property(strong, nonatomic)UITableView *tableView;
@property(strong, nonatomic)QMUIButton *topCalendaBtn;
@property(strong, nonatomic)NSDate *date;
@property(strong, nonatomic)NSMutableArray<NSNumber *> *secArray; //分区数组

@property(strong, nonatomic)NSMutableArray<DBEcgRecord *> *ecgRecArray;//日内的记录

@property(strong, nonatomic)NSMutableArray<EcgResItemObj *> *conclusionObjArray;


@end

@implementation MainEcgVc

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifyDateChange:) name:NOTI_NAME_SLEEP_DATE_CHANGE object:nil];

    
    [self initData];
    [self initUI];

    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.date = [[DeviceCenter instance] currentQueryDate];
    
    [self queryConclusionCnt];
    [self queryDayRecords:self.date];
}

-(void)initData {
    self.secArray = [NSMutableArray new];
    self.ecgRecArray = [NSMutableArray new];
    
    [self.secArray addObjectsFromArray:@[ @(ECG_SEC_RESULTS),
                                          ]];
}

-(void)initUI {
    [self.topCalendaBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@43);
    }];
    self.navigationItem.titleView = self.topCalendaBtn;
    self.navigationController.navigationBar.translucent = NO;
    
    QMUIButton *measuBtn = [[QMUIButton alloc]init];
    [measuBtn setImage:[UIImage imageNamed:@"ecg_nav_btn"] forState:UIControlStateNormal];
    [measuBtn addTarget:self action:@selector(gotoMeasure:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:measuBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view.mas_leading).offset(VC_ITEM_MARGIN_HOR);
        make.trailing.equalTo(self.view.mas_trailing).inset(VC_ITEM_MARGIN_HOR);
        make.top.equalTo(self.tableView.superview.mas_safeAreaLayoutGuideTop);
        make.bottom.equalTo(self.tableView.superview.mas_safeAreaLayoutGuideBottom);
    }];
    
    
}

-(void)notifyDateChange:(NSNotification *)noti {
    
    self.date = [[DeviceCenter instance] currentQueryDate];
    // TODO: 更新头部日期
    // 重新查询
//    [self queryAlldata:self.date];
    [self queryDayRecords:self.date];

}

-(void)gotoMeasure:(QMUIButton *)btn {
    
    if ([DeviceCenter instance].bindDevice.otherInfo.isSupportEcg == NO) {
        [self showAlertWarningWithTitle:@"Tips" Msg:@"This Ring is not support Ecg measurment function." btnOk:_L(L_OK) OkBLk:^{
            
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
        return;
    }
    
    EcgMeasureVc *ecgVc = [[EcgMeasureVc alloc]init];
    ecgVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:ecgVc animated:YES];
}

// 查询日期内的记录
-(void)queryDayRecords:(NSDate *)date {
    if (!date){
        return;
    }
    NSDate *begin = [TimeUtils zeroOfDate:date];
    NSDate *end = [TimeUtils zeroOfNextDayDate:date];
    WEAK_SELF
    [DBEcgRecord queryByTimeRange:[DeviceCenter instance].bindDevice.macAddress BeginDate:begin EndDate:end OrderBeTimeDesc:YES Limit:3 Cpmplete:^(NSMutableArray<DBEcgRecord *> * _Nonnull results) {
        STRONG_SELF
        strongSelf.ecgRecArray = results;
        
        if (strongSelf.ecgRecArray.count) {
            
            self.secArray = [NSMutableArray arrayWithArray:@[ @(ECG_SEC_ITEM),
                                                              @(ECG_SEC_RESULTS),
                                                              ]];

            
        }
        
        if (!strongSelf.ecgRecArray.count) {
            self.secArray = [NSMutableArray arrayWithArray:@[ @(ECG_SEC_MEASU),
                                                              @(ECG_SEC_RESULTS),
                                                             ]];
            
//            if (strongSelf.secArray.firstObject.intValue == ECG_SEC_ITEM) {
//                [strongSelf.secArray removeObjectAtIndex:0];
//
//
//            }
//            [strongSelf.secArray insertObject:@(ECG_SEC_MEASU) atIndex:0];

            
        }
        
        [strongSelf.tableView reloadData];
        
    }];
    
    
}

-(void)queryConclusionCnt {
    
    WEAK_SELF
    [DBEcgRecord queryAllResultCounts:[DeviceCenter instance].bindDevice.macAddress Cpmplete:^(NSMutableDictionary * _Nonnull resultDict) {
        STRONG_SELF
        
        [strongSelf.conclusionObjArray enumerateObjectsUsingBlock:^(EcgResItemObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.count = [resultDict[@(obj.resTag)] intValue];
            
        }];
        [strongSelf.tableView reloadData];
    }];
}




-(void)calendaClick:(id)sender {
    
    // 日历选择
    BasicCalendaVc *calendaVc = [[BasicCalendaVc alloc]init];
    calendaVc.hidesBottomBarWhenPushed = YES;

    WEAK_SELF
    calendaVc.selectDateCBK = ^(NSDate *date) {
        STRONG_SELF
        if (date) {
//            strongSelf.date = date;
            [[DeviceCenter instance] querySleep:date];
            
            [strongSelf queryDayRecords:date];


        }
    };
    
    [self presentViewController:calendaVc animated:YES completion:nil];
    
}

-(void)setDate:(NSDate *)date
{
    _date = date;
    NSDate *now = [NSDate date];
    NSDate *todayZero = [TimeUtils zeroOfDate:now]; // 今天0点
    NSDate *yesterdayZero = [TimeUtils zeroOfBeforeDayDate:now];// 昨天0点
    NSDate *yearDate = [TimeUtils zeroOfYearByDate:now]; // 年初0点
    //    NSDate *tomorrowDate = [TimeUtils zeroOfNextDayDate:now]; // 明天0点
    
    NSTimeInterval todayZeroTimeInterval = [todayZero timeIntervalSince1970];
    NSTimeInterval yesterdayZeroTimeInterval =  [yesterdayZero timeIntervalSince1970];
    NSTimeInterval yearDateTimeInterval =  [yearDate timeIntervalSince1970];
    NSTimeInterval nowTimeInterval = [now timeIntervalSince1970];
    
    NSTimeInterval selectTimeInterval = [_date timeIntervalSince1970];
    
#if DEBUG // debug显式显式日期
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    // 今年内
    if (selectTimeInterval > yearDateTimeInterval) {
        //            DebugNSLog(@"time %@ 昨天以前 今年内", _date);
        formatter.dateFormat = _L(L_TITLE_DATE_IN_THIS_YEAR);
    } else {
        // 今年前
        //            DebugNSLog(@"time %@ 今年以前", _date);
        formatter.dateFormat = _L(L_TITLE_DATE_BEFORE_THIS_YEAR);
        
    }
    NSString *str = [formatter stringFromDate:date];
    [self.topCalendaBtn setTitle:str forState:UIControlStateNormal];
    return;
#endif
    
    
    if (selectTimeInterval > nowTimeInterval) {
        //        DebugNSLog(@"time %@ 现在以后", _date);
        // 超过当前日期
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        
        formatter.dateFormat = _L(L_TITLE_DATE_IN_THIS_YEAR);
        
        NSString *str = [formatter stringFromDate:date];
        [self.topCalendaBtn setTitle:str forState:UIControlStateNormal];
        return;
    }
    
    if (selectTimeInterval <= nowTimeInterval && selectTimeInterval >= todayZeroTimeInterval) {
        // 今天内
        //        DebugNSLog(@"time %@ 今天内", _date);
        [self.topCalendaBtn setTitle:_L(L_TODAY) forState:UIControlStateNormal];
        return;
    }
    
    if (selectTimeInterval >= yesterdayZeroTimeInterval && selectTimeInterval <= todayZeroTimeInterval) {
        // 昨天内
        //        DebugNSLog(@"time %@ 昨天内", _date);
        [self.topCalendaBtn setTitle:_L(L_TITLE_DATE_YESTERDAY) forState:UIControlStateNormal];
        return;
    }
    // [date timeIntervalSinceDate:[NSDate date]] <= 0
    if (selectTimeInterval < yesterdayZeroTimeInterval) {
        // 昨天前
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        // 今年内
        if (selectTimeInterval > yearDateTimeInterval) {
            //            DebugNSLog(@"time %@ 昨天以前 今年内", _date);
            formatter.dateFormat = _L(L_TITLE_DATE_IN_THIS_YEAR);
        } else {
            // 今年前
            //            DebugNSLog(@"time %@ 今年以前", _date);
            formatter.dateFormat = _L(L_TITLE_DATE_BEFORE_THIS_YEAR);
            
        }
        NSString *str = [formatter stringFromDate:date];
        [self.topCalendaBtn setTitle:str forState:UIControlStateNormal];
        return;
    }
    
}

#pragma mark -- tableview
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.secArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.secArray[section].integerValue == ECG_SEC_ITEM)
    {
        return 0;
    }
    if (self.secArray[section].integerValue == ECG_SEC_MEASU) {
        return 15;
    }
    return 50;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.secArray[section].integerValue == ECG_SEC_ITEM ) {
        
        return nil;
    }
    if (self.secArray[section].integerValue == ECG_SEC_MEASU) {
        return [UIView new];
    }
    
    UIView *content = [UIView new];
    UILabel *label = [UILabel new];
    label.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:20];
    label.textColor = UIColor.whiteColor;
    [content addSubview:label];
    [label mainItemTitleStyle];
  
    switch (self.secArray[section].integerValue) {
        case ECG_SEC_RESULTS:
        {
            label.text = _L(L_TITL_ECG_RESULT);
        }
            break;
      
        default:
            break;
    }
    

    label.adjustsFontSizeToFitWidth = YES;
    
    return content;
    
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (self.secArray[section].intValue) {
        case ECG_SEC_ITEM:
        {
            return self.ecgRecArray.count;
        }
            break;
        case ECG_SEC_RESULTS:
        {
            return self.conclusionObjArray.count;
        }
            break;
     
        case ECG_SEC_MEASU:
        {
            return 1;
        }
            break;
        default:
            break;
    }
    
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.secArray[indexPath.section].intValue) {
        case ECG_SEC_ITEM:
        {
            return 220;
        }
            break;
        case ECG_SEC_RESULTS:
        {
            return 45;
        }
            break;
      
        case ECG_SEC_MEASU:
        {
            return 45;

        }
            break;
        default:
            break;
    }
    
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // NormalSetCell @"mainecg_rescell"
    
    switch (self.secArray[indexPath.section].intValue) {
        case ECG_SEC_ITEM:
        {
            EcgListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EcgListCell" forIndexPath:indexPath];
//            cell.hmEcgDrawLineView.direction = [AccountCenter instance].currentAccount.otherInfo.wearHand.intValue;
            cell.ecgRecord = self.ecgRecArray[indexPath.row];
            return cell;
        }
            break;
        case ECG_SEC_RESULTS:
        {
            NormalSetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mainecg_rescell" forIndexPath:indexPath];
            [cell addArrow];
            if (indexPath.row == self.conclusionObjArray.count - 1) {
                [cell removeSepLine];
            } else {
                [cell addSepLine];
            }
            
            cell.textLabel.text = self.conclusionObjArray[indexPath.row].titleString;
            cell.rightLabel.text = [NSString stringWithFormat:@"%ld", (long)self.conclusionObjArray[indexPath.row].count];
            
            return cell;
        }
            break;
        case ECG_SEC_MEASU:
        {
            NormalSetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mainecg_rescell" forIndexPath:indexPath];
            [cell addArrow];
            [cell removeSepLine];
//            if (indexPath.row == self.conclusionObjArray.count - 1) {
//                [cell removeSepLine];
//            } else {
//                [cell addSepLine];
//            }
            
            cell.textLabel.text = _L(L_MEASU_ECG);
            cell.rightLabel.text = nil;
            
            return cell;
            
        }
            break;

            break;
        default:
            break;
    }
    
    
    return nil;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    
    int sectionType = self.secArray[indexPath.section].intValue;
    if (sectionType == ECG_SEC_RESULTS
        || sectionType == ECG_SEC_MEASU) {
        cell.layer.mask = nil;
        [cell addTopBottomCornerRadius:ITEM_BG_COLOR IndexPath:indexPath TableView:tableView CornerRadius:ITEM_CORNOR_RADIUS]; // 首位单元格加圆角
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (self.secArray[indexPath.section].intValue) {
        case ECG_SEC_ITEM:
        {
            EcgDetailVc *vc = [[EcgDetailVc alloc]init];
            vc.ecgRecord = self.ecgRecArray[indexPath.row];
            WEAK_SELF
            vc.deleteCBK = ^(DBEcgRecord * _Nonnull ecgRecord) {
                STRONG_SELF
                [strongSelf.ecgRecArray removeObject:ecgRecord];
                [strongSelf.tableView reloadData];
            };
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case ECG_SEC_MEASU:
        {
            [self gotoMeasure:nil];
            
        }
            break;
        case ECG_SEC_RESULTS:
        {
           // 跳转列表
            EcgRecordsVc *recordVc = [[EcgRecordsVc alloc]init];
            recordVc.conclusionObj = self.conclusionObjArray[indexPath.row];
            recordVc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:recordVc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark --lazy

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UIColor.clearColor;
        
        [_tableView registerClass:[NormalSetCell class] forCellReuseIdentifier:@"mainecg_rescell"];
        [_tableView registerClass:[EcgListCell class] forCellReuseIdentifier:@"EcgListCell"];

        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0.0f;
        }
    }
    
    return _tableView;
}
-(QMUIButton *)topCalendaBtn
{
    if (!_topCalendaBtn) {
        _topCalendaBtn = [[QMUIButton alloc]init];
        _topCalendaBtn.tintColor = MAIN_BLUE;
        [_topCalendaBtn setTitleColor:MAIN_BLUE forState:UIControlStateNormal];
//        _topCalendaBtn.titleLabel.textColor = MAIN_BLUE;
        _topCalendaBtn.adjustsImageTintColorAutomatically = YES;
        _topCalendaBtn.imagePosition = QMUIButtonImagePositionRight;
        [_topCalendaBtn setTitle:_L(L_TODAY) forState:UIControlStateNormal];
        _topCalendaBtn.backgroundColor = UIColor.clearColor;
        [_topCalendaBtn setImage:[UIImage imageNamed:@"icon_calenda"] forState:UIControlStateNormal];
        _topCalendaBtn.spacingBetweenImageAndTitle = 3;
        [_topCalendaBtn addTarget:self action:@selector(calendaClick:) forControlEvents:UIControlEventTouchUpInside];
        // 底部添加一条横线
        UIView *line = [UIView new];
        [_topCalendaBtn addSubview:line];
        line.backgroundColor = MAIN_BLUE;
        [line mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.bottom.equalTo(_topCalendaBtn);
            make.height.equalTo(@1);
        }];
        
    }
    return _topCalendaBtn;
}

-(NSMutableArray<EcgResItemObj *> *)conclusionObjArray
{
    
    
    if (!_conclusionObjArray) {
        _conclusionObjArray = [NSMutableArray new];
        NSArray<NSNumber*> *tagArray = @[ @(MAIN_ECG_RES_ALL_DATA),
                                          @(CONCLUSION_SINUS_RHYTHM) , // 窦性心律
                                          @(CONCLUSION_AFI) ,               // 房颤
                                          @(CONCLUSION_HIGH_HR ),            // 高心率
                                          @(CONCLUSION_LOW_HR) ,             // 低心率
                                          @(CONCLUSION_IN_CONCLUSIVE ),      // 不确定
                                          @(CONCLUSION_POOR_RECORDING ),     // 记录不佳
                                          ];
        [tagArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            EcgResItemObj *itemObj = [[EcgResItemObj alloc]init];
            itemObj.resTag = obj.integerValue;
            [_conclusionObjArray addObject:itemObj];
        }];
        
    }
    return _conclusionObjArray;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end


/// 结果列表的对象
@implementation EcgResItemObj

- (void)setResTag:(NSInteger)resTag
{
    _resTag = resTag;
    
    if (resTag == MAIN_ECG_RES_ALL_DATA) {
        
        self.titleString = _L(L_ALL_DATA);
        
    } else {
        
        self.titleString = [DBEcgRecord titleOfConclusion:resTag];
        
    }
    
}

@end
